<template>
  <div class="page-content">
    <table-bar :showTop="false" :columns="columns" @changeColumn="changeColumn">
      <div slot="top">
        <el-form label-width="70px">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :lg="6">
              <el-form-item label="用户名：">
                <el-input placeholder="用户名"></el-input>
              </el-form-item>
            </el-col>
            <el-row
              :xs="24"
              :sm="12"
              :lg="6"
              style="float: right; margin-right: 10px"
            >
              <el-button type="primary">搜索</el-button>
              <el-button>重置</el-button>
            </el-row>
          </el-row>
        </el-form>
      </div>
      <div slot="bottom">
        <el-button type="primary" plain @click="showDialog('add')"
          >新增商家</el-button
        >
      </div>
    </table-bar>

    <tao-table :data="list" :showPage="true" v-bind:page="page" ref="table">
      <el-table-column label="ID" prop="id" v-if="columns[0].show" />
      <el-table-column label="LOGO" prop="logo" v-if="columns[1].show">
        <template slot-scope="scope">
          <img class="avatar" :src="scope.row.logo" />
        </template>
      </el-table-column>
      <el-table-column label="商家名称" prop="name" v-if="columns[2].show" />
      <el-table-column
        label="商家分类"
        prop="cate_name"
        v-if="columns[3].show"
      />
      <el-table-column label="手机号" prop="phone" v-if="columns[4].show" />
      <el-table-column
        label="结算系数"
        prop="settlement_rate"
        v-if="columns[5].show"
      />
      <el-table-column label="商家收入" prop="income" v-if="columns[6].show" />
      <el-table-column label="订单数" prop="order_num" v-if="columns[7].show" />
      <el-table-column label="状态" prop="status" v-if="columns[8].show">
        <template slot-scope="scope">
          <el-tag size="mini" :type="scope.row.status === 1 ? '' : 'info'">
            {{ scope.row.status === 1 ? "启用" : "禁用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建日期"
        prop="create_time"
        v-if="columns[9].show"
      />
      <el-table-column fixed="right" label="操作" width="150px">
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-edit"
            @click="showDialog('edit')"
          >
            编辑
          </el-button>
          <el-button
            type="text"
            style="color: #fa6962"
            icon="el-icon-delete"
            @click="deleteUser(scope)"
          >
            注销
          </el-button>
        </template>
      </el-table-column>
    </tao-table>

    <el-dialog :title="dialogTitle" width="800px" :visible.sync="dvEdit">
      <el-form ref="form" :model="form" label-width="auto">
        <el-tabs v-model="activeName">
          <el-tab-pane label="基本信息" name="basic" :key="'basic'">
            <div>
              <el-form-item
                label="选择代理"
                v-if="userInfo.role_type == 'admin'"
                prop="agent_id"
              >
                <el-select
                  v-model="form.agent_id"
                  placeholder="请选择所属代理"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in agentList"
                    :key="item.id"
                    :value="item.id"
                    :label="item.name"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="商户名称" prop="name">
                <el-input v-model="form.name"></el-input>
              </el-form-item>
              <el-form-item label="选择分类" prop="cate_id">
                <el-select
                  v-model="form.cate_id"
                  placeholder="请选择商家分类"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in cateList"
                    :key="item.id"
                    :value="item.id"
                    :label="item.name"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="电话" prop="phone">
                <el-input v-model="form.phone"></el-input>
              </el-form-item>
              <el-form-item label="所在城区" prop="district_id">
                <el-cascader
                  style="width: 100%"
                  v-model="form.district_id"
                  :options="cityTree"
                  :props="{
                    expandTrigger: 'click',
                    checkStrictly: false,
                    value: 'id',
                    label: 'Name',
                    children: 'child',
                  }"
                  @change="handleChange"
                ></el-cascader>
              </el-form-item>
              <el-form-item label="详细地址" prop="address_detail">
                <el-input v-model="form.address_detail"></el-input>
              </el-form-item>
              <el-form-item label="营业时间" prop="business_hours">
                <el-input
                  v-model="form.business_hours"
                  placeholder="例如：周一  至  周五     早8:00~晚8:00"
                ></el-input>
              </el-form-item>
            </div>
          </el-tab-pane>
          <el-tab-pane label="资质" name="certificate" :key="'certificate'">
            <div>
              <el-form-item label="商家LOGO">
                <el-upload
                  :action="upload_url"
                  list-type="picture-card"
                  :class="{ disabled: uploadDisabled }"
                  :on-success="handleUploadLogoSuccess"
                  :show-file-list="true"
                  :on-preview="handleImagePreview"
                  :on-remove="handleLogoRemove"
                  :on-change="handleLogoChange"
                  :before-upload="handleLogoBeforeUpoload"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog
                  :visible.sync="dialogVisible"
                  :modal-append-to-body="false"
                >
                  <img width="100%" :src="dialogImageUrl" alt="" />
                </el-dialog>
              </el-form-item>
              <el-form-item label="营业执照">
                <el-upload
                  :action="upload_url"
                  list-type="picture-card"
                  :on-success="handleUploadBusinessLicenseSuccess"
                  :show-file-list="true"
                  :on-preview="handleImagePreview"
                  :on-remove="handleBusinessLicenseRemove"
                  :on-change="handleBusinessLicenseChange"
                  :before-upload="handleBusinessLicenseBeforeUpoload"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
              </el-form-item>
              <el-form-item label="食品营业许可证">
                <el-upload
                  :action="upload_url"
                  list-type="picture-card"
                  :on-success="handleUploadFoodBusinessLicenseSuccess"
                  :show-file-list="true"
                  :on-preview="handleImagePreview"
                  :on-remove="handleFoodBusinessLicenseRemove"
                  :on-change="handleFoodBusinessLicenseChange"
                  :before-upload="handleFoodBusinessLicenseBeforeUpoload"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
              </el-form-item>
            </div>
          </el-tab-pane>
          <el-tab-pane label="结算信息" name="settle" :key="'settle'">
            <div>
              <el-form-item label="结算费率" prop="settlement_rate">
                <el-input
                  v-model="form.settlement_rate"
                  placeholder="请输入结算费率，如不填写，则为默认费率"
                ></el-input>
              </el-form-item>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dvEdit = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { getAllAgent } from "@/api/agentApi.js";
import { getAddressTree } from "@/api/addressApi.js";
import { getBusinessAllCate, getBuinessList } from "@/api/businessApi.js";
import { baseUrl } from "@/utils/config.js";

export default {
  data() {
    return {
      hideUpload: false,
      dialogVisible: false,
      dialogImageUrl: "",
      imageUrl: "",
      upload_url: baseUrl + "/admin/ajax/upload",
      activeName: "basic",
      dvEdit: false,
      dialogTitle: "",
      form: {
        id:0,
        name: "",
        phone: "",
        cate_id: "",
        logo: "",
        business_license: "",
        food_business_license: "",
        business_imgs: [],
        district_id: 0,
        address_detail: "",
        business_hours: "",
        settlement_rate: "",
      },
      value: "",
      list: [],
      columns: [
        { name: "ID", show: true },
        { name: "LOGO", show: true },
        { name: "商家名称", show: true },
        { name: "商家分类", show: true },
        { name: "手机号", show: true },
        { name: "结算系数", show: true },
        { name: "商家收入", show: true },
        { name: "订单数", show: true },
        { name: "状态", show: true },
        { name: "创建日期", show: true },
      ],
      agentList: [],
      cateList: [],
      cityTree: [],
      page: {
        total: 0,
        page: 1,
        pagesize: 15,
      },
    };
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.user.info,
    }),
  },
  mounted() {
    getBuinessList(this.page).then((res) => {
      if (res.code == 0) {
        this.list = res.data.data;
        this.page.total = res.data.count;
      }
    });
  },
  methods: {
    handleLogoChange(file, fileList) {
      this.hideUpload = fileList.length >= this.limitCount;
    },
    handleUploadLogoSuccess(res, file, fileList) {
      console.log("上传成功调用了", this.form);
      console.log("当前表单信息", this.form);
      //this.form.logo = URL.createObjectURL(file.raw);
      this.form.logo = res.data;
    },
    handleLogoBeforeUpoload(file) {
      console.log("上传前处理调用了", this.form);
      console.log("当前表单信息", this.form);
      if (this.form.logo) {
        this.$message({
          type: "error",
          message: "请删除后再上传",
        });
        return false;
      }
      console.log("上传前处理调用后乐的点点滴滴", this.form);
      console.log("当前表单信息", this.form);
    },
    handleLogoRemove(file, fileList) {
      console.log("进入移除", this.form);
      console.log("当前表单信息", this.form);
      //this.form.logo = "";
      if (file && file.status === "success") {
        console.log("调用了移除", this.form);
        console.log("当前表单信息", this.form);
        this.form.logo = "";
      }
    },
    handleUploadBusinessLicenseSuccess(res, file, fileList) {
      console.log("@@@@@", fileList);
      // this.form.business_license = URL.createObjectURL(file.raw);
      this.form.business_license = res.data;
    },
    handleBusinessLicenseBeforeUpoload(file) {
      console.log("当前表单信息", this.form);
      if (this.form.business_license) {
        this.$message({
          type: "error",
          message: "请删除后再上传",
        });
        return false;
      }
    },
    handleBusinessLicenseRemove(file, fileList) {
      console.log("进入移除", this.form);
      console.log("当前表单信息", this.form);
      //this.form.logo = "";
      if (file && file.status === "success") {
        console.log("调用了移除", this.form);
        console.log("当前表单信息", this.form);
        this.form.business_license = "";
      }
    },
    handleUploadFoodBusinessLicenseSuccess(res, file, fileList) {
      console.log("当前表单信息", this.form);
      //this.form.food_business_license = URL.createObjectURL(file.raw);
      this.form.food_business_license = res.data;
    },
    handleFoodBusinessLicenseBeforeUpoload(file) {
      console.log("当前表单信息", this.form);
      if (this.form.food_business_license) {
        this.$message({
          type: "error",
          message: "请删除后再上传",
        });
        return false;
      }
    },
    handleFoodBusinessLicenseRemove(file, fileList) {
      console.log("@@@@@2222", fileList);

      if (file && file.status === "success") {
        console.log("调用了移除", this.form);
        console.log("当前表单信息", this.form);
        this.form.food_business_license = "";
      }
    },
    changePage(page, limit) {
      this.page.page = page;
      this.page.pageSize = limit;
      getBuinessList(this.page).then((res) => {
        if (res.code == 0) {
          this.list = res.data.data;
          this.page.total = res.data.count;
        }
      });
    },
    showDialog(type) {
      this.dvEdit = true;
      this.dialogTitle = type === "add" ? "新增商家" : "编辑商家";
      if (this.userInfo.role_type == "admin") {
        this.getAllAgent();
      }
      this.getCityTree();
      this.getBusinessCate();
    },
    onSubmit(form) {
      this.dvEdit = false;
      this.$refs[form].validate((valid) => {
        if (valid) {
          this.dvEdit = false;
          editBusiness(this.form).then((res) => {
            if (res.code == 0) {
              this.$message({
                message: res.msg,
                type: "success",
              });
              getBuinessList(this.page).then((res) => {
                if (res.code == 0) {
                  this.list = res.data.data;
                  this.page.total = res.data.count;
                }
              });
            } else {
              this.$message({
                message: res.msg,
                type: "error",
              });
            }
          });
        }
      });
    },
    getAllAgent() {
      getAllAgent({}).then((res) => {
        if (res.code == 0) {
          this.agentList = res.data;
        }
      });
    },
    getCityTree() {
      getAddressTree().then((res) => {
        console.log("address tree", res);
        if (res.code == 0) {
          this.cityTree = res.data;
        }
      });
    },
    getBusinessCate() {
      getBusinessAllCate().then((res) => {
        if (res.code == 0) {
          this.cateList = res.data;
        }
      });
    },

    deleteUser(scope) {
      this.$confirm("您确定要注销当前用户吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
      })
        .then(() => {
          this.userList.splice(scope.$index, 1);
        })
        .catch(() => {});
    },
    changeColumn(columns) {
      this.columns = columns;
      this.$refs.table.doLayout();
    },

    handleImagePreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
  },
};
</script>

<style lang='scss' scoped>
.page-content {
  width: 100%;
  height: 100%;

  .avatar {
    width: 50px;
    height: 50px;
    //border-radius: 50%;
  }
}
</style>
